import {defineStore} from 'pinia'
import {ref, watch} from 'vue'
import {
  defaultActiveChatId,
  defaultChatContent,
  defaultChatUserListMap,
  defaultIsLoaded,
  defaultNewMessageCount
} from '@/store/chat/config'
import {cloudGeneralObjectCustomUI} from '@/uniCloud-alipay'

//定义聊天store
const useChatStore = defineStore('chat', () => {
  //聊天列表
  const chatUserListMap = ref(defaultChatUserListMap)
  //聊天内容
  const chatContent = ref(defaultChatContent)
  //是否加载过
  const isLoaded = ref(defaultIsLoaded)
  const isContentLoaded = ref(defaultIsLoaded)
  //新消息个数
  const newMessageCount = ref(defaultNewMessageCount)
  //当前活跃聊天
  const activeChatId = ref(defaultActiveChatId)

  //获取聊天列表
  const fetchChatListAction = async () => {
    const newMap = new Map()
    const res = (await cloudGeneralObjectCustomUI.getInfoByTwoTable('chat', 'user')).data

    const active = activeChatId.value
    const length = chatContent.value.length
    await fetchChatContentAction()

    res.forEach(item => newMap.set(item._id, item))
    chatUserListMap.value = newMap

    if (!activeChatId.value) activeChatId.value = res[0]._id
    isLoaded.value = true

    //判断聊天内容是否有变化
    if (active === activeChatId.value && length === chatContent.value.length) return

    return true
  }

  //获取聊天内容
  const fetchChatContentAction = async () => {
    chatContent.value = (await cloudGeneralObjectCustomUI.getListByField('chat_content', 'chat_id', activeChatId.value)).data
  }

  watch(activeChatId, async () => {
    isContentLoaded.value = defaultIsLoaded
    await fetchChatContentAction()
    isContentLoaded.value = true
  })

  //发送聊天内容
  const fetchPushChatAction = async (text) => {
    const time = Date.now()
    await cloudGeneralObjectCustomUI.updateDataById('chat', activeChatId.value, {
      recent_time: time,
      recent_text: text
    })

    //推送聊天数组（type:  0客服   1用户）
    await cloudGeneralObjectCustomUI.insertData('chat_content', {
      chat_id: activeChatId.value,
      type: 0,
      text,
      time: Date.now()
    })

    //更新缓存数据
    chatUserListMap.value.get(activeChatId.value).recent_time = time
    chatUserListMap.value.get(activeChatId.value).recent_text = text

    await fetchChatContentAction()
  }

  //恢复默认
  const resetStateAction = () => {
    //将加载状态设为默认值
    isLoaded.value = defaultIsLoaded
  }

  return {
    chatUserListMap,
    chatContent,
    isLoaded,
    newMessageCount,
    activeChatId,
    isContentLoaded,
    fetchChatListAction,
    fetchPushChatAction,
    resetStateAction
  }
})

export default useChatStore
